<template>
  <view class="create-order-page">
    <!-- 顶部导航 -->
    <uni-nav-bar 
      title="代客下单" 
      left-icon="left" 
      :border="false"
      background-color="#fff"
      @clickLeft="handleBack"
    />

    <scroll-view scroll-y class="form-content">
      <uni-forms ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <!-- 门店选择 -->
        <uni-forms-item label="选择门店" name="store_id" required>
          <uni-data-select
            v-model="formData.store_id"
            :localdata="storeOptions"
            placeholder="请选择门店"
            @change="onStoreChange"
          ></uni-data-select>
        </uni-forms-item>

        <!-- 场地选择 -->
        <uni-forms-item label="选择场地" name="venue_id" required>
          <uni-data-select
            v-model="formData.venue_id"
            :localdata="venueOptions"
            placeholder="请选择场地"
            :disabled="!formData.store_id"
          ></uni-data-select>
        </uni-forms-item>

        <!-- 会员选择 -->
        <uni-forms-item label="选择会员" name="member_id" required>
          <view class="member-selector" @click="showMemberPicker">
            <text v-if="selectedMember" class="member-text">
              {{ selectedMember.name }} ({{ selectedMember.phone }})
            </text>
            <text v-else class="placeholder-text">请选择会员</text>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </uni-forms-item>

        <!-- 预定时间 -->
        <uni-forms-item label="开始时间" name="start_time" required>
          <uni-datetime-picker
            v-model="formData.start_time"
            type="datetime"
            placeholder="请选择开始时间"
            @change="onStartTimeChange"
          ></uni-datetime-picker>
        </uni-forms-item>

        <uni-forms-item label="结束时间" name="end_time" required>
          <uni-datetime-picker
            v-model="formData.end_time"
            type="datetime"
            placeholder="请选择结束时间"
            @change="onEndTimeChange"
          ></uni-datetime-picker>
        </uni-forms-item>

        <!-- 场地可用性检查结果 -->
        <view v-if="availabilityStatus" class="availability-status">
          <uni-icons 
            :type="availabilityStatus.available ? 'checkmarkempty' : 'closeempty'" 
            :color="availabilityStatus.available ? '#52c41a' : '#ff4d4f'"
            size="16"
          ></uni-icons>
          <text :class="availabilityStatus.available ? 'available-text' : 'unavailable-text'">
            {{ availabilityStatus.message }}
          </text>
        </view>

        <!-- 备注信息 -->
        <uni-forms-item label="备注信息" name="remark">
          <uni-easyinput
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入备注信息（可选）"
            :maxlength="200"
          ></uni-easyinput>
        </uni-forms-item>

        <!-- 预估金额显示 -->
        <view v-if="estimatedAmount > 0" class="amount-info">
          <view class="amount-label">预估金额：</view>
          <view class="amount-value">¥{{ (estimatedAmount / 100).toFixed(2) }}</view>
        </view>
      </uni-forms>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="form-footer safe-area-inset-bottom">
      <button class="submit-btn" :disabled="!canSubmit" :loading="submitting" @click="handleSubmit">
        {{ submitting ? '提交中...' : '确认下单' }}
      </button>
    </view>

    <!-- 会员选择弹窗 -->
    <uni-popup ref="memberPopup" type="bottom">
      <view class="member-popup safe-area-inset-bottom">
        <view class="popup-header">
          <text class="popup-title">选择会员</text>
          <uni-icons type="closeempty" size="20" color="#999" @click="memberPopup.close()"></uni-icons>
        </view>
        
        <!-- 会员搜索 -->
        <view class="member-search">
          <uni-easyinput
            v-model="memberSearchKeyword"
            prefixIcon="search"
            placeholder="搜索会员姓名或手机号"
            @input="searchMembers"
          ></uni-easyinput>
        </view>

        <!-- 会员列表 -->
        <scroll-view scroll-y class="member-list">
          <view 
            v-for="member in filteredMembers" 
            :key="member.id"
            class="member-item"
            @click="selectMember(member)"
          >
            <view class="member-info">
              <text class="member-name">{{ member.name }}</text>
              <text class="member-phone">{{ member.phone }}</text>
            </view>
            <uni-icons 
              v-if="formData.member_id === member.id"
              type="checkmarkempty" 
              color="var(--primary-color)" 
              size="20"
            ></uni-icons>
          </view>
          
          <view v-if="filteredMembers.length === 0" class="empty-members">
            <uni-icons type="info" size="40" color="#999"></uni-icons>
            <text class="empty-text">暂无匹配的会员</text>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { fetchStoreList } from '@/api/order';
import { createOrderForCustomer, checkTimeSlotAvailability } from '@/api/order';
// 定义本地类型接口
interface Store {
  id: number;
  name: string;
  address?: string;
  status?: number;
}

interface Venue {
  id: number;
  name: string;
  store_id: number;
}

interface Member {
  id: number;
  name: string;
  phone: string;
}

// 表单数据
const formData = reactive({
  store_id: null as number | null,
  venue_id: null as number | null,
  member_id: null as number | null,
  start_time: '',
  end_time: '',
  remark: '',
});

// 表单验证规则
const rules = {
  store_id: {
    rules: [{ required: true, errorMessage: '请选择门店' }]
  },
  venue_id: {
    rules: [{ required: true, errorMessage: '请选择场地' }]
  },
  member_id: {
    rules: [{ required: true, errorMessage: '请选择会员' }]
  },
  start_time: {
    rules: [{ required: true, errorMessage: '请选择开始时间' }]
  },
  end_time: {
    rules: [{ required: true, errorMessage: '请选择结束时间' }]
  },
};

// 数据状态
const stores = ref<Store[]>([]);
const venues = ref<Venue[]>([]);
const members = ref<Member[]>([]);
const filteredMembers = ref<Member[]>([]);
const selectedMember = ref<Member | null>(null);
const memberSearchKeyword = ref('');
const submitting = ref(false);
const estimatedAmount = ref(0);
const availabilityStatus = ref<{ available: boolean; message: string } | null>(null);

// 引用
const formRef = ref();
const memberPopup = ref();

// 计算属性
const storeOptions = computed(() => 
  stores.value.map(store => ({ value: store.id, text: store.name }))
);

const venueOptions = computed(() => 
  venues.value.map(venue => ({ value: venue.id, text: venue.name }))
);

const canSubmit = computed(() => {
  return formData.store_id && 
         formData.venue_id && 
         formData.member_id && 
         formData.start_time && 
         formData.end_time &&
         availabilityStatus.value?.available &&
         !submitting.value;
});

// 获取门店列表
const getStores = async () => {
  try {
    const res = await fetchStoreList();
    stores.value = res;
  } catch (error) {
    console.error('获取门店列表失败:', error);
    uni.showToast({ title: '获取门店列表失败', icon: 'none' });
  }
};

// 获取会员列表
const getMembers = async () => {
  try {
    // 模拟会员数据，实际应该调用会员API
    const mockMembers = [
      { id: 1, name: '张三', phone: '13800138001' },
      { id: 2, name: '李四', phone: '13800138002' },
      { id: 3, name: '王五', phone: '13800138003' },
    ];
    members.value = mockMembers;
    filteredMembers.value = mockMembers;
  } catch (error) {
    console.error('获取会员列表失败:', error);
    uni.showToast({ title: '获取会员列表失败', icon: 'none' });
  }
};

// 门店变更处理
const onStoreChange = async (storeId: number) => {
  formData.venue_id = null;
  venues.value = [];
  availabilityStatus.value = null;
  
  if (storeId) {
    try {
      // 模拟场地数据，实际应该调用场地API
      const mockVenues = [
        { id: 1, name: '会议室A', store_id: storeId },
        { id: 2, name: '会议室B', store_id: storeId },
        { id: 3, name: '培训室C', store_id: storeId },
      ];
      venues.value = mockVenues;
    } catch (error) {
      console.error('获取场地列表失败:', error);
      uni.showToast({ title: '获取场地列表失败', icon: 'none' });
    }
  }
};

// 时间变更处理
const onStartTimeChange = () => {
  checkAvailability();
  calculateEstimatedAmount();
};

const onEndTimeChange = () => {
  checkAvailability();
  calculateEstimatedAmount();
};

// 检查场地可用性
const checkAvailability = async () => {
  if (!formData.venue_id || !formData.start_time || !formData.end_time) {
    availabilityStatus.value = null;
    return;
  }

  const startTime = new Date(formData.start_time).getTime() / 1000;
  const endTime = new Date(formData.end_time).getTime() / 1000;

  if (endTime <= startTime) {
    availabilityStatus.value = {
      available: false,
      message: '结束时间必须晚于开始时间'
    };
    return;
  }

  try {
    const res = await checkTimeSlotAvailability({
      venue_id: formData.venue_id,
      start_time: startTime,
      end_time: endTime
    });
    availabilityStatus.value = {
      available: res.available,
      message: res.available ? '场地可用' : '场地在此时间段已被占用'
    };
  } catch (error) {
    console.error('检查场地可用性失败:', error);
    availabilityStatus.value = {
      available: false,
      message: '检查场地可用性失败'
    };
  }
};

// 计算预估金额
const calculateEstimatedAmount = () => {
  if (!formData.start_time || !formData.end_time) {
    estimatedAmount.value = 0;
    return;
  }

  const startTime = new Date(formData.start_time);
  const endTime = new Date(formData.end_time);
  const hours = (endTime.getTime() - startTime.getTime()) / (1000 * 60 * 60);
  
  // 假设每小时100元，实际应该根据场地价格计算
  estimatedAmount.value = Math.ceil(hours) * 10000; // 转换为分
};

// 显示会员选择器
const showMemberPicker = () => {
  memberPopup.value.open();
};

// 搜索会员
const searchMembers = () => {
  const keyword = memberSearchKeyword.value.toLowerCase();
  if (!keyword) {
    filteredMembers.value = members.value;
  } else {
    filteredMembers.value = members.value.filter(member => 
      member.name.toLowerCase().includes(keyword) || 
      member.phone.includes(keyword)
    );
  }
};

// 选择会员
const selectMember = (member: Member) => {
  formData.member_id = member.id;
  selectedMember.value = member;
  memberPopup.value.close();
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate();
    
    if (!availabilityStatus.value?.available) {
      uni.showToast({ title: '场地不可用，请重新选择', icon: 'none' });
      return;
    }

    submitting.value = true;

    const submitData = {
      store_id: formData.store_id!,
      venue_id: formData.venue_id!,
      member_id: formData.member_id!,
      start_time: new Date(formData.start_time).getTime() / 1000,
      end_time: new Date(formData.end_time).getTime() / 1000,
      remark: formData.remark,
    };

    await createOrderForCustomer(submitData);
    
    uni.showToast({ title: '下单成功', icon: 'success' });
    
    // 返回订单列表页面
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);

  } catch (error: any) {
    console.error('下单失败:', error);
    uni.showToast({ 
      title: error.message || '下单失败', 
      icon: 'none' 
    });
  } finally {
    submitting.value = false;
  }
};

// 返回上一页
const handleBack = () => {
  uni.navigateBack();
};

// 监听场地变更
watch(() => formData.venue_id, () => {
  checkAvailability();
});

onLoad((options: any) => {
  getStores();
  getMembers();
});
</script>

<style lang="scss" scoped>
.create-order-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.form-content {
  flex: 1;
  height: 0;
  padding: 15px;
  padding-bottom: 80px;
}

.member-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;

  .member-text {
    color: var(--text-color);
    font-size: 14px;
  }

  .placeholder-text {
    color: var(--text-color-placeholder);
    font-size: 14px;
  }
}

.availability-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  margin: 10px 0;
  border-radius: var(--border-radius);
  background-color: #f5f5f5;

  .available-text {
    color: #52c41a;
    font-size: 14px;
  }

  .unavailable-text {
    color: #ff4d4f;
    font-size: 14px;
  }
}

.amount-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  margin: 15px 0;
  background-color: #fff;
  border-radius: var(--border-radius);
  box-shadow: var(--shadow);

  .amount-label {
    font-size: 16px;
    color: var(--text-color);
  }

  .amount-value {
    font-size: 18px;
    font-weight: bold;
    color: var(--error-color);
  }
}

.form-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 15px;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);

  .submit-btn {
    width: 100%;
    height: 44px;
    background-color: var(--primary-color);
    color: #fff;
    border-radius: var(--border-radius);
    font-size: 16px;
    margin: 0;

    &[disabled] {
      background-color: #ccc;
      color: #999;
    }
  }
}

.member-popup {
  background-color: #fff;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  max-height: 70vh;
  display: flex;
  flex-direction: column;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #eee;

    .popup-title {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .member-search {
    padding: 15px;
    border-bottom: 1px solid #eee;
  }

  .member-list {
    flex: 1;
    height: 0;
    max-height: 400px;

    .member-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px;
      border-bottom: 1px solid #f0f0f0;

      .member-info {
        flex: 1;

        .member-name {
          display: block;
          font-size: 16px;
          color: var(--text-color);
          margin-bottom: 4px;
        }

        .member-phone {
          font-size: 14px;
          color: var(--text-color-secondary);
        }
      }
    }

    .empty-members {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 50px 20px;
      color: #999;

      .empty-text {
        margin-top: 10px;
        font-size: 14px;
      }
    }
  }
}
</style>